package com.coman404.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * @author NotFound404 at 2024/6/1
 * code code always code
 */
public class MyHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private String basePath;

    public MyHttpServerHandler(String basePath) {
        this.basePath = basePath;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        String methodName = msg.method().name();
        String requestUri = msg.uri();
        if (!"GET".equals(methodName)) {
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer("Not Support".getBytes()));
            response.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            return ;
        }
        this.sendResponse(requestUri,ctx);
    }

    private void sendResponse(String uri,ChannelHandlerContext ctx) throws IOException {
        String filename = "index";
        String path = uri.substring(0,uri.lastIndexOf("/"));
        if (!"/".equals(uri)){
            //请求
            filename = uri.substring(uri.lastIndexOf("/")+1);
        }
        System.out.println(String.format("path:%s,filename:%s", path, filename));
        File file = new File(basePath + path + "/" + filename+".html");
        if (!file.exists()){
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
            response.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
            return;
        }
        //读取文件到buf中返回
        RandomAccessFile accessFile = new RandomAccessFile(file,"r");
        FileChannel fileChannel = accessFile.getChannel();
        ByteBuf buf = Unpooled.wrappedBuffer(fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length()));
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,buf);
        response.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/html");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
